package com.byc.adbcommandline;

import androidx.annotation.NonNull;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 命令行操作工具类
 */
public class ShellUtils {
    private static final String COMMAND_SU = "su"; // 获取root权限的命令
    private static final String COMMAND_SH = "sh"; // 执行sh文件的命令
    private static final String COMMAND_EXIT = "exit\n"; // 退出的命令
    private static final String COMMAND_LINE_END = "\n"; // 执行命令必须加在末尾


    // TODO: 2022/10/17 ------------详细的ADB命令在程序中执行----------------------start----------------

    /**
     * 卸载APP（需要root权限）
     * @param packageName 要卸载的APP包名
     * @return 返回内容
     */
    public static String UNINSTALL_APP(String packageName){
        return String.format("pm uninstall -k %s",packageName);
    }
    /**
     * 按包名启动APP（需要root权限）
     * @param packageName 要启动的APP包名
     * @return 返回内容
     */
    public static String START_APP_BY_PACKAGE_NAME(String packageName) {
        return String.format("monkey -p %s -c android.intent.category.LAUNCHER 1", packageName);
    }
    /**
     * 关闭APP（需要root权限）
     * @param packageName 要关闭的APP包名
     * @return 返回内容
     */
    public static String STOP_APP(String packageName){
        return String.format("am force-stop %s",packageName);
    }
    /**
     * 查看APP详细信息（需要root权限）
     * @param packageName 要获取的APP包名
     * @return 返回内容
     */
    public static String GET_APP_MESSAGE(String packageName){
        return String.format("dumpsys package %s",packageName);
    }
    /**
     * 启动默认浏览器打开一个网页（需要root权限）
     * @param webUrl 要打开的网页地址
     * @return 返回内容
     */
    public static String OPEN_WEB(String webUrl){
        return String.format("am start -a android.intent.action.VIEW -d %s",webUrl);
    }
    /**
     * 打开系统设置（需要root权限）
     */
    public static final String OPEN_SETTINGS = "am start com.android.settings";
    /**
     * 获取三方应用包名
     */
    public static final String GET_APP_3 = "pm list packages -3";
    /**
     * 获取应用安装位置
     */
    public static final String GET_APP_INSTALL_LOCATION = "pm get-install-location";

    /**
     * 获取设备Android系统版本
     */
    public static final String GET_DEVICE_ANDROID_VERSION = "getprop ro.build.version.release";
    /**
     * 获取设备型号
     */
    public static final String GET_DEVICE_MODEL = "getprop ro.product.model";
    /**
     * 获取AndroidId（需要root权限）
     */
    public static final String GET_DEVICE_ANDROID_ID = "settings get secure android_id";
    /**
     * 获取设备Mac地址
     */
    public static final String GET_DEVICE_MAC = "cat /sys/class/net/wlan0/address";
    /**
     * 获取设备屏幕分辨率
     */
    public static final String GET_DEVICE_DISPLAY = "wm size";
    /**
     * 获取屏幕像素密度
     */
    public static final String GET_DEVICE_DENSITY = "wm density";

    /**
     * 移动文件（需要root权限）
     * @param filePath 待移动的文件路径
     * @param targetPath 移动到的文件路径（包含文件名及后缀）
     * @return 返回命令
     */
    public static String REMOVE_FILE(String filePath,String targetPath){
        return String.format("mv -f %s %s",filePath,targetPath);
    }

    /**
     * 删除文件（需要root权限）
     * @param filePath 文件地址
     * @return 返回内容
     */
    public static String DELETE_FILE(String filePath){
        return String.format("rm %s",filePath);
    }

    /**
     * home键（需要root权限）
     */
    public static final String KEY_HOME = "input keyevent 3";
    /**
     * 返回键
     */
    public static final String KEY_BACK = "input keyevent 4";
    /**
     * 菜单键（需要root权限）
     */
    public static final String KEY_MENU = "input keyevent 82";
    /**
     * 音量放大
     */
    public static final String KEY_VOICE_UP = "input keyevent 24";
    /**
     * 音量缩小
     */
    public static final String KEY_VOICE_DOWN = "input keyevent 25";
    /**
     * 静音及解除静音
     */
    public static final String KEY_VOICE_MUTE_OR_NOT = "input keyevent 164";
    /**
     * 提高屏幕亮度（需要root权限）
     */
    public static final String KEY_SCREEN_LIGHT_UP = "input keyevent 221";
    /**
     * 降低屏幕亮度（需要root权限）
     */
    public static final String KEY_SCREEN_LIGHT_DOWN = "input keyevent 220";
    // TODO: 2022/10/17 ------------详细的ADB命令在程序中执行-----------------------end-----------------

    private ShellUtils() {
        throw new AssertionError();
    }

    //检测root状态
    public static boolean checkRootPermission() {
        return execCommand("echo root", true, false).result == 0;
    }

    //执行单行命令,实际还是调用的执行多行 ,传入命令和是否需要root
    public static CommandResult execCommand(String command, boolean isRoot) {
        return execCommand(new String[]{command}, isRoot, true);
    }

    //执行List<String>中的命令 , 传入List和是否需要root
    public static CommandResult execCommand(List<String> commands, boolean isRoot) {
        return execCommand(commands == null ? null : commands.toArray(new String[]{}), isRoot, true);
    }

    //执行多行命令
    public static CommandResult execCommand(String[] commands, boolean isRoot) {
        return execCommand(commands, isRoot, true);
    }

    private static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
        return execCommand(new String[]{command}, isRoot, isNeedResultMsg);
    }

    public static CommandResult execCommand(List<String> commands, boolean isRoot, boolean isNeedResultMsg) {
        return execCommand(commands == null ? null : commands.toArray(new String[]{}), isRoot, isNeedResultMsg);
    }

    //执行命令,获得返回的信息
    private static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, null);
        }

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command == null) {
                    continue;
                }
                os.write(command.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
            }
            os.writeBytes(COMMAND_EXIT);
            os.flush();

            result = process.waitFor();
            // get command result
            if (isNeedResultMsg) {
                successMsg = new StringBuilder();
                errorMsg = new StringBuilder();
                successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s);
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (process != null) {
                process.destroy();
            }
        }
        return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
                : errorMsg.toString());
    }

    //封装了返回信息
    public static class CommandResult {

        public final int result;
        public String successMsg; //成功信息
        public String errorMsg; // 错误信息

        public CommandResult(int result) {
            this.result = result;
        }

        CommandResult(int result, String successMsg, String errorMsg) {
            this.result = result;
            this.successMsg = successMsg;
            this.errorMsg = errorMsg;
        }

        @NonNull
        @Override
        public String toString() {
            return "CommandResult{" +
                    "result=" + result +
                    ", successMsg='" + successMsg + '\'' +
                    ", errorMsg='" + errorMsg + '\'' +
                    '}';
        }
    }
}